package com.tsd.openweixin.controller;

import com.tsd.common.controller.BaseController;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.openweixin.model.AccessToken;
import com.tsd.core.openweixin.model.JsapiTicket;
import com.tsd.core.openweixin.utils.WechatUtils;
import com.tsd.core.openweixin.utils.WeixinSign;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.vo.HttpResult;
import com.tsd.system.service.SysSettingService;
import com.tsd.system.vo.MpSetting;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 微信公众号相关
 */
@Controller
@Scope("prototype")
@RequestMapping("/wx")
public class WeixinMpController extends BaseController {
    @Resource
    SysSettingService sysSettingService;

    @ApiOperation(value = "微信公众号页面授权签名")
    @ResponseBody
    @RequestMapping(value = "/getMpPageAuthSign.action")
    public HttpResult<Object> getMpPageAuthSign() {
        HttpResult<Object> hr = new HttpResult<>();
        try {
            Map<String, Object> params = super.getParams(request);
            String url = HlpUtils.getString(params, "url");
            super.checkEmpty(url, "缺少参数url");
            String datasource = DataSourceContextHolder.getDataSourceType();
            MpSetting mpSetting = sysSettingService.queryValidSettingByCode(MpSetting.SETTING_CODE_WX_MP, MpSetting.class);
            super.checkEmpty(mpSetting, "没有配置微信公众号设置");
            super.checkEmpty(mpSetting.getWechat_app_id(), "微信公众号appid未设置");
            super.checkEmpty(mpSetting.getWechat_app_secret(), "微信公众号密钥未设置");
            AccessToken access_token = WechatUtils.getAccessToken(mpSetting.getWechat_app_id(), mpSetting.getWechat_app_secret());
            JsapiTicket jsapiTicket = WechatUtils.getJsapiTicket(access_token.getToken());
            Map<String, String> map = WeixinSign.sign(mpSetting.getWechat_app_id(), jsapiTicket.getTicket(), url);
            hr.setData(map);
        } catch (Exception e) {
            super.procException(hr, e);
        }
        return hr;
    }

}
